<template>
  <div style="margin-top: 20px">
    <!-- ECharts 饼图容器 -->
    <div ref="chartContainer" style="width: 100%; height: 600px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { useUserStore } from "../../../stores/user.ts";
import * as echarts from 'echarts';
import {
  ClubControllerService,
  type ClubMemberQueryRequest,
  type ClubMembershipVO,
} from "../../../../generated";

// 定义成员数据结构
interface Member {
  userId: number;
  username: string;
  role: string;
  grade: string;
  major: string;class: string;
  contact: string;
}

const store = useUserStore();
const memberList = ref<Member[]>([]);
const totalItems = ref(0);
const clubMemberQueryRequest = ref<ClubMemberQueryRequest>({
  pageSize: 10,
  current: 1,clubId: store.managedClubId,userName: "",
});

const chartContainer = ref<HTMLElement | null>(null);

const loadData = async () => {
  const res = await ClubControllerService.listUserVoInClubByPage(
      clubMemberQueryRequest.value,);
  if (res.code === 0) {
    const userVoList = res.data?.records as ClubMembershipVO[];
    memberList.value = userVoList.map(
        (memberShipVO) =>
            ({
              userId: memberShipVO.userVO?.id,
              username: memberShipVO.userVO?.userName,
              role: memberShipVO.identity === "member" ? "成员" : "社长",
              grade: memberShipVO.userVO?.grade,
              major: memberShipVO.userVO?.major || "未填写", // 将未填写专业的成员标记为"未填写"
              class: memberShipVO.userVO?.userClass,
              contact: memberShipVO.userVO?.phoneNumber,
            }) as Member,
    );
    totalItems.value = userVoList.length;
    updateChart();
  } else {
    ElMessage.error("加载数据失败：" + res.message);
  }
};

const majorDistribution = computed(() => {
  const distribution = memberList.value.reduce((acc, member) => {
    const major = member.major || "未填写";
    acc[major] = (acc[major] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  return Object.entries(distribution).map(([name, value]) => ({ name, value }));
});

const updateChart = () => {
  if (chartContainer.value) {
    const chart = echarts.init(chartContainer.value);
    const option = {
      title: {
        text: '社团成员专业分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '专业分布',
          type: 'pie',
          radius: '50%',
          data: majorDistribution.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    chart.setOption(option);
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
/* 您可以在这里添加任何需要的样式 */
</style>